const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');

let pathToClean = ['dist'];
let isProd = process.env.NODE_ENV === 'production';
let cssDev = ['style-loader', 'css-loader', 'sass-loader'];
let cssProd = ExtractTextPlugin.extract({
  fallback: 'style-loader',
  use: ['css-loader', 'sass-loader']
});
let cssConfig = isProd ? cssProd : cssDev;
const webpackConfig = {
  entry: {
    app: './src/app.js',
    contact: './src/contact.js',
    pug: './src/pug.js',
    image: './src/image.js'
  },
  output: {
    path: path.resolve(__dirname + '/dist'),
    filename: '[name].[hash].js'
  },
  devServer: {
    port: 9000,
    open: true,
    hot: true
  },
  plugins: [
    new CleanPlugin(pathToClean),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, './src/pug.pug'),
      filename: 'pug.html',
      minify: {
        collapseWhitespace: true
      },
      hash: true,
      chunks: ['pug']
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, './src/image.html'),
      filename: 'image.html',
      minify: {
        collapseWhitespace: true
      },
      hash: true,
      chunks: ['image']
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, './src/index.html'),
      filename: 'index.html',
      minify: {
        collapseWhitespace: true
      },
      hash: true,
      chunks: ['app']
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, './src/contact.html'),
      filename: 'contact.html',
      minify: {
        collapseWhitespace: true
      },
      hash: true,
      chunks: ['contact']
    }),
    new ExtractTextPlugin({
      filename: '[name].css',
      disable: !isProd
    })
  ],
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: cssConfig
      },
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ },
      {
        test: /\.pug$/,
        loader: ['raw-loader', 'pug-html-loader'],
        exclude: /node_modules/
      },
      {
        test: /\.(gif|png|jpe?g|svg)$/i,
        use: [
          {
            loader: 'file-loader',
            options: { name: '[name].[ext]', outputPath: 'images/' }
          },
          {
            loader: 'image-webpack-loader',
            options: {
              bypassOnDebug: true
            }
          }
        ]
      },
      {
        test: /\.html$/,
        use: [{ loader: 'html-loader', options: { minimize: true } }]
      }
    ]
  }
};

module.exports = webpackConfig;
